package com.yozinga.fragment;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.yozinga.R;
import com.yozinga.entity.Place;
import com.yozinga.entity.PlacesList;
import com.yozinga.util.AlertDialogManager;
import com.yozinga.util.GooglePlaces;
import com.yozinga.util.SinglePlaceInfo;
import com.yozinga.util.SinglePlaceInfo.ListListener;


public class ChangeLocationDialogFragment extends DialogFragment implements OnItemClickListener{

	private double _latitude;
	private double _longitude;
	private double _radius;

	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();


	// Places List
	PlacesList nearPlaces;

	// Button
	Button btnShowOnMap;

	// Progress dialog
	ProgressDialog pDialog;

	// Google Places
	GooglePlaces googlePlaces;

	// ListItems data
	ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();

	// KEY Strings
	public static String KEY_REFERENCE = "reference"; // id of the place
	public static String KEY_NAME = "name"; // name of the place
	public static String KEY_VICINITY = "vicinity"; // Place area name

	ListView listView;
	Context mContext;
	ListListener mListener;

	public ChangeLocationDialogFragment(double latitude, double longitude, double radius,ListListener listlistener) {
		this._latitude = latitude;
		this._longitude = longitude;
		this._radius = radius;
		mListener = listlistener;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		getDialog().setTitle("Choose Location");
		View v = inflater.inflate(R.layout.fragment_sharedialog, container, false);
		listView = (ListView) v.findViewById(android.R.id.list);
		listView.setOnItemClickListener(this);
		return v;
	}
	
	

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		new LoadPlaces().execute();
	}
	class LoadPlaces extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		/*@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}*/

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			// creating Places class object
			googlePlaces = new GooglePlaces();

			try {
				// Separeate your place types by PIPE symbol "|"
				// If you want all types places make it as null
				// Check list of types supported by google
				// 
				//String types = "cafe|restaurant"; // Listing places only cafes, restaurants

				// Radius in meters - increase this value if you don't find any places
				//double radius = 1000; // 1000 meters 

				// get nearest places
				nearPlaces = googlePlaces.search(_latitude,
						_longitude, _radius, null);

				Log.i("Today","List size is: "+nearPlaces.results.size());

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * and show the data in UI
		 * Always use runOnUiThread(new Runnable()) to update UI from background
		 * thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			//pDialog.dismiss();

			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed Places into LISTVIEW
					 * */
					// Get json response status
					String status = nearPlaces.status;

					// Check for all possible status
					if(status.equals("OK")){
						// Successfully got places details
						if (nearPlaces.results != null) {
							// loop through each place
							for (Place p : nearPlaces.results) {
								HashMap<String, String> map = new HashMap<String, String>();

								// Place reference won't display in listview - it will be hidden
								// Place reference is used to get "place full details"
								map.put(KEY_REFERENCE, p.reference);

								// Place name
								map.put(KEY_NAME, p.name);


								// adding HashMap to ArrayList
								placesListItems.add(map);
							}
							// list adapter
							ListAdapter adapter = new SimpleAdapter(getActivity(), placesListItems,
									R.layout.list_item,
									new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
								R.id.reference, R.id.name });

							// Adding data into listview
							listView.setAdapter(adapter);
						}
					}
					/*else if(status.equals("ZERO_RESULTS")){
						// Zero results found
						alert.showAlertDialog(getActivity(), "Near Places",
								"Sorry no places found. Try to change the types of places",
								false);
					}
					else if(status.equals("UNKNOWN_ERROR"))
					{
						alert.showAlertDialog(getActivity(), "Places Error",
								"Sorry unknown error occured.",
								false);
					}
					else if(status.equals("OVER_QUERY_LIMIT"))
					{
						alert.showAlertDialog(getActivity(), "Places Error",
								"Sorry query limit to google places is reached",
								false);
					}
					else if(status.equals("REQUEST_DENIED"))
					{
						alert.showAlertDialog(getActivity(), "Places Error",
								"Sorry error occured. Request is denied",
								false);
					}
					else if(status.equals("INVALID_REQUEST"))
					{
						alert.showAlertDialog(getActivity(), "Places Error",
								"Sorry error occured. Invalid Request",
								false);
					}
					else
					{
						alert.showAlertDialog(getActivity(), "Places Error",
								"Sorry error occured.",
								false);
					}*/
				}
			});

		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		// getting values from selected ListItem
		String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
		String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
		new SinglePlaceInfo(getActivity(), reference,mListener,name);
		dismiss();
	}
}
